// v-throttle 指令：用于按钮、输入框等事件节流

export default {
  mounted(el, binding) {
    let last = 0;
    const delay = binding.arg ? parseInt(binding.arg) : 1000;
    const event = binding.modifiers.input ? 'input' : 'click';
    const handler = binding.value;
    if (typeof handler !== 'function') return;
    el.__throttleHandler__ = function (...args) {
      const now = Date.now();
      if (now - last > delay) {
        last = now;
        handler.apply(this, args);
      }
    };
    el.addEventListener(event, el.__throttleHandler__);
  },
  beforeUnmount(el, binding) {
    const event = binding.modifiers.input ? 'input' : 'click';
    el.removeEventListener(event, el.__throttleHandler__);
    delete el.__throttleHandler__;
  }
};
